package com.yan_jiu_sheng.LeetCodeHot100.AC;

import java.util.Deque;
import java.util.LinkedList;

/**
 * https://leetcode.cn/problems/decode-string/description/?envType=study-plan-v2&envId=top-100-liked
 * AC 通过
 *
 * @author yulongTian
 * @create 2024-07-10 17:12
 */
public class Test69 {
    public static void main(String[] args) {
        System.out.println(new Test69().decodeString("3[z]2[2[y]pq4[2[jk]e1[f]]]ef"));
    }

    public String decodeString(String s) {
        StringBuilder ans = new StringBuilder();

        Deque<Character> deque = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 'a' && c <= 'z' && deque.isEmpty()) {
                ans.append(c);
                continue;
            }

            if (c == ']') {
                StringBuilder temp_s = new StringBuilder();
                while (!deque.isEmpty() && deque.peek() != '[') {
                    temp_s.append(deque.pop());
                }
                deque.pop();
                //计算次数
                StringBuilder temp_time_s = new StringBuilder();
                int times = 0;
                while (!deque.isEmpty() && deque.peek() >= '0' && deque.peek() <= '9') {
                    temp_time_s.append(deque.pop());
                }
                times = Integer.valueOf(temp_time_s.reverse().toString());
                if (deque.isEmpty()) {
                    //为空 记录答案
                    StringBuilder reverse = temp_s.reverse();
                    for (int j = 0; j < times; j++) {
                        ans.append(reverse);
                    }
                } else {
                    // 不为空
                    StringBuilder reverse = temp_s.reverse();
                    for (int j = 0; j < times; j++) {
                        for (int k = 0; k < reverse.length(); k++) {
                            deque.push(reverse.charAt(k));
                        }
                    }
                }
                continue;
            }
            deque.push(c);
        }

        return ans.toString();
    }
}
